package br.com.ebc.icontatos.converter;

import javax.annotation.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import br.com.ebc.icontatos.model.Pais;
import br.com.ebc.icontatos.repository.PaisRepository;

public class PaisConverter implements Converter{

	@Resource
	private PaisRepository paisDAO;
	
	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if (value == null || value.length() == 0 || value.equals("-- Selecione --")) {
            return null;
        }
		
		Long id = new Long(value);
		Pais p = new Pais();
		p.setIdPais(id);
		p = paisDAO.find(p.getIdPais());
		return p;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null) {
            return null;
        }
		
		if(value instanceof Pais){
			Pais p = (Pais) value;
			return p.getIdPais() == null ? "" : p.getIdPais().toString(); 
		} else {
			throw new IllegalArgumentException("object " + value + " is of type " + value.getClass().getName() + "; expected type: model.Pais");
		}
	}

	public PaisRepository getPaisDAO() {
		return paisDAO;
	}

	public void setPaisDAO(PaisRepository paisDAO) {
		this.paisDAO = paisDAO;
	}

}
